package com.xipu.yygh.manage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xipu.yygh.common.exception.YyghException;
import com.xipu.yygh.feign.service_cmn.CmnFeignClient;
import com.xipu.yygh.manage.repository.HospManageRepository;
import com.xipu.yygh.manage.service.HospManageService;
import com.xipu.yygh.model.hosp.BookingRule;
import com.xipu.yygh.model.hosp.Hospital;
import com.xipu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description: 医院管理Service
 * @author: gql
 * @date: 2022/05
 */
@Service
public class HospManageServiceImpl implements HospManageService {

    /**
     * 医院信息表(MongoDB)
     */
    @Autowired
    private HospManageRepository hospManageRepository;

    /**
     * 数据字典表(MySQL)
     */
    @Autowired
    private CmnFeignClient cmnFeignClient;

    /**
     * 将Map<String, Object>中的值加到MongoDB中
     *      使用FastJSON把Map变成Hospital对象
     * @param resultMap 医院传过来的数据
     */
    @Override
    public void saveHosp(Map<String, Object> resultMap) {
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(resultMap), Hospital.class);
        if (StringUtils.isEmpty(hospital)) {
            throw new YyghException(20001, "上传数据异常!");
        } else {
            Hospital existHospital = hospManageRepository.findByHoscode(hospital.getHoscode());
            if (!StringUtils.isEmpty(existHospital)) {
                // 修改
                hospital.setId(existHospital.getId());
                hospital.setCreateTime(existHospital.getCreateTime());
                hospital.setStatus(existHospital.getStatus());
            } else {
                //添加
                hospital.setCreateTime(new Date());
                hospital.setStatus(0);
            }
            hospital.setIsDeleted(0);
            hospital.setUpdateTime(new Date());
            hospManageRepository.save(hospital);
        }
    }

    /**
     * 根据hoscode查询医院信息
     * @param hoscode 医院编码
     * @return 医院信息
     */
    @Override
    public Hospital getHospital(String hoscode) {
        Hospital hospital = this.hospManageRepository.findByHoscode(hoscode);
        if (StringUtils.isEmpty(hospital)) {
            throw new YyghException(20000, "查询失败");
        } else {
            return hospital;
        }
    }

    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        // 1.设置排序规则
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        // 2.设置分页数据
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        // 3.条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        // 4.将hospitalQueryVo转换为hospital
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        hospital.setIsDeleted(0);

        // 5.封装查询条件
        Example<Hospital> example = Example.of(hospital, matcher);

        // 6.执行查询
        Page<Hospital> pages = this.hospManageRepository.findAll(example, pageable);

        // 7.远程调用获取编号对应的名称
        List<Hospital> list = pages.getContent();
        list.forEach(item -> {
            packageHosp(item);
        });
        return pages;
    }

    /**
     * 封装数据字典编号对应的名称
     * @param item i
     */
    private void packageHosp(Hospital item) {
        // 医院等级
        String hostype = cmnFeignClient.getName("Hostype", item.getHostype());
        // 省
        String province = cmnFeignClient.getName(item.getProvinceCode());
        // 市
        String city = cmnFeignClient.getName(item.getCityCode());
        // 区
        String district = cmnFeignClient.getName(item.getDistrictCode());
        // 封装到item的属性中
        item.getParam().put("hostype", hostype);
        item.getParam().put("fullAddress", province + city + district + item.getAddress());
    }

    @Override
    public Map<String, Object> show(String id) {
        // 1.查询到hospital信息
        Hospital hospital = this.hospManageRepository.findById(id).get();

        // 2.封装编号对应的名称
        this.packageHosp(hospital);

        // 3.创建返回结果集
        Map<String, Object> result = new HashMap<>();
        // 3.1添加医院基本信息（包含医院等级）
        result.put("hospital", hospital);
        // 3.2添加预约规则bookingRule
        result.put("bookingRule", hospital.getBookingRule());

        // 4.医院基本信息不需要预约规则
        hospital.setBookingRule(null);
        return result;
    }

    @Override
    public List<Hospital> findByHosname(String hosname) {
        return this.hospManageRepository.findByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> getHospDetail(String hoscode) {
        Hospital hospital = this.getHospital(hoscode);
        this.packageHosp(hospital);

        Map<String, Object> map = new HashMap<>();
        map.put("hospital", hospital);
        map.put("bookingRule", hospital.getBookingRule());

        hospital.setBookingRule(null);
        return map;
    }

    @Override
    public BookingRule getHospitalByHoscode(String hoscode) {
        Hospital hospital = this.hospManageRepository.findByHoscode(hoscode);
        if (StringUtils.isEmpty(hospital)) {
            throw new YyghException(20001, "医院信息为空");
        } else {
            return hospital.getBookingRule();
        }
    }
}
